package x10.enums;

import java.util.EnumSet;
import java.util.HashMap;

/**
 *  Function - enumeration of X10 function codes (on, off, etc.) along with utility methods
 *  to create the nibble values for powerline and radio frequency versions
 *  and static methods for creating a function object
 *
 *  @author Denny Sheirer
 *  @date   20110124
 */

public enum Function {
    ALL_UNITS_OFF(0),
    ALL_LIGHTS_ON(1),
    ON(2),
    OFF(3),
    DIM(4),
    BRIGHT(5),
    ALL_LIGHTS_OFF(6),
    EXTENDED_CODE_1(7),   //Used to be just Extended Code (pre-2000)
    HAIL_REQUEST(8),
    HAIL_ACKNOWLEDGE(9),
    EXTENDED_CODE_3(10),  //Used to be Preset Dim(1) (pre-2000)
    UNUSED(11),           //Used to be Preset Dim(2) (pre-2000)
    EXTENDED_CODE_2(12),  //Used to be Extended Data Transfer (pre-2000)
    STATUS_ON(13),
    STATUS_OFF(14),
    STATUS_REQUEST(15),
    UNKNOWN(16);          // Null equivalent

    private final int code;

    //Lookups to convert from integer to Function code
    private static final HashMap<Integer,Function> lookup = new HashMap<Integer,Function>();

    //Hidden class to populate the lookup hashmap
    static {
        for(Function f : EnumSet.allOf(Function.class)){
            lookup.put(f.code, f);
        }
    }

    /**
     * Constructor
     * @param functionCode
     */
    Function(int functionCode){
        this.code = functionCode;
    }

    /**
     * Utility method to return the byte representation of the function code 
     * in the lower nibble.  Byte value is the integer (code) value
     * @return
     */
    public byte getByteValue(){
        return (byte) this.code;
    }

    /**
     * Utility method to instantiate a function object from the integer
     * representation of the byte version of the function code.
     * 
     * @param functionCode
     * @return
     */
    public static Function getFunction(int functionCode){
        return lookup.get(functionCode);
    }
}
